#!/bin/bash

wait_ipport() {
    local ipport=$1 #e.g. "10.10.153.11:18888"
    local loop=100
    while true; do
        ss -lnt |grep -w "$ipport" &>/dev/null
        [ $? -eq 0 ] && return 0
        sleep 0.5
        ((loop--))
        # timeout
        [ $loop -eq 0 ] && return 1
    done
}

kill_ipport() {
    # LISTEN    0    128    10.10.153.11:18888    *:*    users:(("ssh",pid=28610,fd=5))
    local ipport=$1 #e.g. "10.10.153.11:18888"
    local pid=
    while true; do
        # e.g. pid=28610
        ss -lntp |grep -w "$ipport"
        eval $(ss -lntp |grep -w "$ipport"|cut -d ',' -f 2)
        if [ ! -z "$pid" ]; then
            kill $pid
            sleep 1
            pid=
            continue
        fi
        break
    done
}

get_vault_file() {
  local vault=
  [ -d ~/.vault ] || { mkdir -p ~/.vault && chmod 700 ~/.vault; } 
  vault=~/.vault/$(basename $1)
  [ -f $1 ] && /bin/cp -f $1 $vault
  if [ ! -f "$vault" ]; then
     echo "vault file $vault not found" >&1
     return 1
  fi
  chmod 600 $vault
  echo $vault
}

load_vault() {
  local vault=$(get_vault_file $1)
  . $vault || { echo "fatal: load vault error." >&1; return 1; }
}

detect_page_endless() {
    local count=6
    local url=$1
    local keyword="$2"

    while true; do
        curl -sk $url |grep "$keyword" &>/dev/null
        if [ $? -ne 0 ]; then
            if [ $count -eq 0 ]; then
                return 1
            fi
            ((count--))
            sleep 5
            continue
        fi
        #echo "detect_page_endless $keyword succeed."
        count=6
        sleep 30
    done
}

